package com.ruoyi.boat.udp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

//@Component // 有需要再打开
public class UdpServer {

    @Value("${udp.server.port}")
    private Integer udpPort;

    @Autowired
    UdpMsgHandler udpMsgHandler; // 需要一个实现

    @PostConstruct
    public void start() {
        new Thread(this::startUdpReceiver).start();
    }

    private void startUdpReceiver() {
        try (DatagramSocket socket = new DatagramSocket(udpPort)) {
            byte[] buffer = new byte[1024];

            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);

                // 获取发来的IP地址和端口号
                InetAddress senderAddress = packet.getAddress();
                int senderPort = packet.getPort();

                // 处理收到的数据
                udpMsgHandler.process(packet.getData(), packet.getLength());
//                udpMsgHandler.process(new String(packet.getData(), 0, packet.getLength())); // 或者处理字符串


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
